package com.applet.mallappletbackstage.controller;


import com.applet.mallappletbackstage.entity.Admin;
import com.applet.mallappletbackstage.entity.User;
import com.applet.mallappletbackstage.entity.vo.AdminRegisterVO;
import com.applet.mallappletbackstage.entity.vo.AdminSessionVo;
import com.applet.mallappletbackstage.service.AdminService;
import com.applet.mallappletbackstage.utils.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author X
 * @since 2020-08-07
 */
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    /***
     * 管理员注册
     * @param adminRegisterVO
     * @return
     */
    @PostMapping("/registerAdmin")
    public R registerAdmin(@RequestBody AdminRegisterVO adminRegisterVO) {
        int count = adminService.registerAdmin(adminRegisterVO);
        if (count > 0) {
            return R.success("注册成功");
        }
        return R.fail("注册失败");
    }

    /***
     * 管理员登录
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/loginAdmin")
    public R loginAdmin(@RequestParam String username,
                        @RequestParam String password,
                        HttpServletRequest request) {
        Admin admin = adminService.loginAdmin(username, password);
        if (!StringUtils.isEmpty(admin)) {
            String adminUsername = admin.getUsername();
            //封装
            AdminSessionVo adminSessionVo = new AdminSessionVo();
            adminSessionVo.setUsername(adminUsername);
            request.getSession().setAttribute("adminSession",adminSessionVo);
            return R.success("登录成功");
        }
        return R.fail("账号或用户名错误");
    }

    /**
     * 获取用户列表
     * @param current
     * @return
     */
    @GetMapping("user-list/{current}")
    public R getUserList(@PathVariable(value = "current") Long current) {
        Page<Admin> adminPage = adminService.getUserList(current);
        return R.success(adminPage);
    }
}

